package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.admin.service.IQuestionService;
import com.shop.admin.validate.question.QuestionCreateValidate;
import com.shop.admin.validate.question.QuestionSearchValidate;
import com.shop.admin.validate.question.QuestionUpdateValidate;
import com.shop.admin.validate.commons.PageValidate;
import com.shop.admin.vo.question.QuestionDetailVo;
import com.shop.admin.vo.question.QuestionListedVo;
import com.shop.common.core.PageResult;
import com.shop.common.entity.Category;
import com.shop.common.entity.Question;
import com.shop.common.enums.CategoryTypeEnum;
import com.shop.common.mapper.CategoryMapper;
import com.shop.common.mapper.QuestionMapper;
import com.shop.common.util.ListUtils;
import com.shop.common.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 试题实现类
 * @author DragonDean
 */
@Service
public class QuestionServiceImpl implements IQuestionService {
        
    @Resource
    QuestionMapper questionMapper;

    @Resource
    CategoryMapper categoryMapper;

    /**
     * 试题列表
     *
     * @author DragonDean
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<QuestionListedVo>
     */
    @Override
    public PageResult<QuestionListedVo> list(PageValidate pageValidate, QuestionSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");

        questionMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:type:int",
            "=:categoryId@category_id:int",
            "like:title:str",
            "=:keywords:str",
        });

        IPage<Question> iPage = questionMapper.selectPage(new Page<>(page, limit), queryWrapper);

        // 查找全部分类并转成Map
        List<Category> allCategory = categoryMapper.selectList(new QueryWrapper<Category>()
                .eq("is_delete", 0)
                .eq("type", CategoryTypeEnum.QUESTION.getCode()));
        Map<Integer, String> categoryMap = ListUtils.listToMap(allCategory, "id", "name");

        List<QuestionListedVo> list = new LinkedList<>();
        for(Question item : iPage.getRecords()) {
            QuestionListedVo vo = new QuestionListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            vo.setCategoryName(categoryMap.get(item.getCategoryId()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 试题详情
     *
     * @author DragonDean
     * @param id 主键参数
     * @return Question
     */
    @Override
    public QuestionDetailVo detail(Integer id) {
        Question model = questionMapper.selectOne(
                new QueryWrapper<Question>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        QuestionDetailVo vo = new QuestionDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 试题新增
     *
     * @author DragonDean
     * @param createValidate 参数
     */
    @Override
    public void add(QuestionCreateValidate createValidate) {
        Question model = new Question();
        model.setType(createValidate.getType());
        model.setCategoryId(createValidate.getCategoryId());
        model.setTitle(createValidate.getTitle());
        model.setOptions(createValidate.getOptions());
        model.setExplanation(createValidate.getExplanation());
        model.setKeywords(createValidate.getKeywords());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        questionMapper.insert(model);
    }

    /**
     * 试题编辑
     *
     * @author DragonDean
     * @param updateValidate 参数
     */
    @Override
    public void edit(QuestionUpdateValidate updateValidate) {
        Question model = questionMapper.selectOne(
                new QueryWrapper<Question>()
                    .eq("id",  updateValidate.getId())
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setType(updateValidate.getType());
        model.setCategoryId(updateValidate.getCategoryId());
        model.setTitle(updateValidate.getTitle());
        model.setOptions(updateValidate.getOptions());
        model.setExplanation(updateValidate.getExplanation());
        model.setKeywords(updateValidate.getKeywords());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        questionMapper.updateById(model);
    }

    /**
     * 试题删除
     *
     * @author DragonDean
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        Question model = questionMapper.selectOne(
                new QueryWrapper<Question>()
                    .eq("id", id)
                    .eq("is_delete", 0)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        questionMapper.updateById(model);
    }

}
